package com.kb.mapper.es;

import com.google.common.collect.ImmutableMap;
import com.kb.util.HashUtil;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.AnalyzeRequest;
import org.elasticsearch.client.indices.AnalyzeResponse;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class ComponentHistoryDao {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${es.index.component_history}")
    private String componentSearchHistoryName;

    private static int DEVIDE_LENGTH = 10;

    private final RestHighLevelClient client;

    private final ElasticsearchOperations elasticsearchOperations;

    public ComponentHistoryDao(RestHighLevelClient client, ElasticsearchOperations elasticsearchOperations) {
        this.client = client;
        this.elasticsearchOperations = elasticsearchOperations;
    }

//    @Async("threadPool-es")
    public void insertSearchHistory(List<String> keywords) {
        try {
            for (String keyword : keywords) {
                // 将关键字切成词根，然后放入SearchPinyin字段供拼音搜索，SearchTerm字段供关键字搜索
                AnalyzeRequest request = AnalyzeRequest.withIndexAnalyzer(componentSearchHistoryName, "ik", keyword);
                AnalyzeResponse response = client.indices().analyze(request, RequestOptions.DEFAULT);
                List<String> terms = response.getTokens().stream().map(AnalyzeResponse.AnalyzeToken::getTerm).filter(x -> x.length() > 1).collect(Collectors.toList());

                if (keyword.length() > DEVIDE_LENGTH) {
                    for (String term : terms) {
                        String id = HashUtil.generateMurmurHash(term);

                        UpdateRequest updateRequest = new UpdateRequest(componentSearchHistoryName, id)
                                .script(new Script(ScriptType.STORED, null, "increment_search_count", new HashMap<>()))
                                .upsert(ImmutableMap.of("search_term", term, "search_pinyin", term, "search_count", 1));

                        // 执行更新请求
                        client.update(updateRequest, RequestOptions.DEFAULT);
                        logger.info("insert search history success, id = {}", id);
                    }
                } else {
                    if (!terms.contains(keyword)) {
                        terms.add(keyword);
                    }
                    String id = HashUtil.generateMurmurHash(keyword);

                    UpdateRequest updateRequest = new UpdateRequest(componentSearchHistoryName, id)
                            .script(new Script(ScriptType.STORED, null, "increment_search_count", new HashMap<>()))
                            .upsert(ImmutableMap.of("search_term", keyword, "search_pinyin", terms, "search_count", 1));

                    // 执行更新请求
                    client.update(updateRequest, RequestOptions.DEFAULT);
                    logger.info("insert search history success, id = {}", id);
                }
            }
        } catch (IOException e) {
            logger.error("insert search history error", e);
        }
    }

}
